package cn.itsource.user.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.user.contants.UserContants;
import cn.itsource.user.domain.LoginInfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.domain.dto.UserDto;
import cn.itsource.user.mapper.LoginInfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.service.IUserService;
import cn.itsource.utils.MD5Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;


    @Override
    public LoginInfo login(User user) {
        //验证 用户名/手机号/邮箱 是否正确
        LoginInfo loginInfo =loginInfoMapper.login(user.getUsername());
        System.out.println(loginInfo);
        if (loginInfo==null){
            throw new RuntimeException("用户名或密码错误");
        }
        //校验 密码是否正确    //用户的输入的密码加盐加密
        String byMd5 = MD5Utils.encrypByMd5(user.getPassword() + loginInfo.getSalt());
        if (!byMd5.equals(loginInfo.getPassword())){
            throw new RuntimeException("用户名或密码错误");
        }

        return loginInfo;

    }

    @Override
    public User loadByPhone(String phone) {
        return userMapper.loadByPhone(phone);
    }

    @Override
    public void register(UserDto userDto) {
        //还是要做一些简单的验证
        //1.校验验证码是否正确
        String codeInRedis =(String)redisTemplate.opsForValue().get(UserContants.REGISTER_CODE+":"+userDto.getPhone());
        String code = codeInRedis.split(":")[0];
        if (!code.equals(userDto.getCode())){
            throw  new RuntimeException("验证码错误，请重新输入");
        }
        User user =userDto2User(userDto);

        //放到数据库里面
        userMapper.save(user);
        //存放到loginInfo里面
        LoginInfo loginInfo =user2LoginInfo(user);
        loginInfoMapper.save(loginInfo);
    }



    private LoginInfo user2LoginInfo(User user) {
        LoginInfo info = new LoginInfo();
        //数据的拷贝
        BeanUtils.copyProperties(user,info);
        //单独处理不能拷贝的字段
        info.setDisable(1);
        info.setType(1);
        info.setUId(user.getId());
        return info;
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setPhone(userDto.getPhone());
        //密码 加密以后存储
        //每一个用户有一个盐值
        String salt = UUID.randomUUID().toString();
        //对密码进行加密
        String byMd5 = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(byMd5);
        //存储盐
        user.setSalt(salt);

        //默认为启用的状态
        user.setState(1);
        return user;
    }
}
